const jwt = require('jsonwebtoken'),
	  path = require('path'),
	  config = require(path.join(__dirname, '../../config.js'))
class Router {
	constructor() {
		this.rules = {
			"get":{},
			"post":{},
			"delete":{},
			"put":{},
			"options":{},
			"patch":{},
			"trace":{},
			"connect":{},
		}
	}
	async use(event){
		if (!event.httpMethod || !event.path){
			return {
				"code":404,
				"data":{},
				"msg":'资源申请错误，请检查method和path'
			}
		}
		const method = event.httpMethod.toLowerCase()
		const path = event.path
		
		//格式化body的json
		if (method === 'post' && event.body) {
			try{
				event.body = JSON.parse(event.body)
			}catch(err){
				event.body = event.body.toString()
			}
		}
		if (!this.rules[method][path]){
			return {
				"code":404,
				"data":{},
				"msg":'资源不存在'
			}
		}else{
			const e = this.rules[method][path]
			if (e.ifJwt){
				console.log(event.headers.token)
				if (!event.headers.token){
					return {
						"code":444,
						"data":{},
						"msg":'请求缺少 Token'
					}
				}
				let decoded = jwt.verify(event.headers.token, config.secret)
				if (config.users[decoded.username] !== decoded.password){
					return {
						"code":444,
						"data":{},
						"msg":'Token 已经过期'
					}
				}
			}
			const pack = require(e.packPath)
			return await pack(event)
		}
	}
	/***
	* path 访问路径
	* packPath 解析的js文件地址，需要绝对路径
	* ifJwt 是否需要token验证
	*/
	get(path, packPath, ifJwt = true){
		this.rules.get[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	post(path, packPath, ifJwt = true){
		this.rules.post[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	delete(path, packPath, ifJwt = true){
		this.rules.delete[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	put(path, packPath, ifJwt = true){
		this.rules.put[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	options(path, packPath, ifJwt = true){
		this.rules.options[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	patch(path, packPath, ifJwt = true){
		this.rules.patch[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	trace(path, packPath, ifJwt = true){
		this.rules.trace[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
	connect(path, packPath, ifJwt = true){
		this.rules.connect[path] = {
			"packPath":packPath,
			"ifJwt": ifJwt
		}
	}
}

module.exports = Router